package com.exception;

import com.alibaba.fastjson.JSONException;
import com.entity.ApiResponse;
import com.enums.ServiceExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

/**
 * 非法异常
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class);

    //业务数据相关异常
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public ApiResponse handle(ServiceExceptionEnum e){
        if(null == e){
            return ApiResponse.error();
        }else{
            return ApiResponse.error(e);
        }
    }

    //空指针异常处理
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ApiResponse handle(NullPointerException e){
        logger.error("空指针异常处理(E01012)",e);
        return ApiResponse.error(ServiceExceptionEnum.NULL_POINT_EXCEPTION);
    }

    //调用外部接口返回500处理
    @ExceptionHandler(value = JSONException.class)
    @ResponseBody
    public ApiResponse handle(JSONException e){
        logger.error("调用外部接口返回500处理(E02013)",e);
        return ApiResponse.error(ServiceExceptionEnum.OUTSIDE_RESOURCE_RESPONSE_ERR);
    }

    //下标越界异常
    @ExceptionHandler(value = ArrayIndexOutOfBoundsException.class)
    @ResponseBody
    public ApiResponse handle(ArrayIndexOutOfBoundsException e){
        logger.error("下标越界异常(E01011)",e);
        return ApiResponse.error(ServiceExceptionEnum.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION);
    }

    //索引越界异常
    @ExceptionHandler(value = IndexOutOfBoundsException.class)
    @ResponseBody
    public ApiResponse handle(IndexOutOfBoundsException e){
        logger.error("索引越界异常(E01010)",e);
        return ApiResponse.error(ServiceExceptionEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION);
    }

    //sql异常
    @ExceptionHandler(value = SQLException.class)
    @ResponseBody
    public ApiResponse handle(SQLException e){
        logger.error("sql异常(E01009)",e);
        return ApiResponse.error(ServiceExceptionEnum.SQL_EXCEPTION);
    }

    //请求方式异常
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ApiResponse handle(HttpRequestMethodNotSupportedException e){
        logger.error("Http请求方式异常(E01008)",e);
        return ApiResponse.error(ServiceExceptionEnum.REQUEST_METHOD_NOT_SUPPORTED_EXCEPTION);
    }

    //统一的异常处理
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResponse handle(Exception e){
        logger.error("其他异常(E00001)",e);
        return ApiResponse.error(ServiceExceptionEnum.OTHER_ABNORMAL);
    }
}
